<template>
  <div
    class="source"
    v-loading="pageLoading"
    :element-loading-text="loadingText"
  >
    <div class="producter-center">
      <v-notes>
        <div class="filterStyle">
          <el-form
            label-width="160px"
            :model="searchList"
            ref="searchForm"
            class="search-form"
            size="small"
          >
            <el-row class="search-row">
              <el-col :span="24">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="商品名称">
                      <el-input
                        placeholder="商品名称"
                        v-model="searchList.productName"
                        @input="searchList.productName=searchList.productName.replace(/\s+/g,'')"
                        clearable
                        v-on:keyup.enter.native="fetchList()"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="SPU编码">
                      <el-input
                        placeholder="SPU编码"
                        v-model="searchList.spuCode"
                        clearable
                        v-on:keyup.enter.native="fetchList()"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="状态">
                      <el-select
                        v-model="searchList.spuStatus"
                        style="width: 100%"
                        placeholder="状态"
                        popper-class="select-class"
                        :popper-append-to-body="false"
                      >
                        <el-option label="全部" value></el-option>
                        <el-option
                          v-for="item in lookupItems.PRODUCTSTATUS"
                          :key="item.id"
                          :label="item.dicName"
                          :value="item.dicCode"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-collapse-transition>
                  <div class="filterContent" v-if="showContent">
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <el-form-item label="商品类型">
                          <el-select
                            v-model="searchList.productTypeCode"
                            placeholder="商品类型"
                            style="width: 95%"
                          >
                            <el-option key label="全部" value></el-option>
                            <el-option
                              v-for="item in lookupItems.PRODUCTTYPE"
                              :key="item.id"
                              :label="item.dicName"
                              :value="item.dicCode"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="后台目录">
                          <el-cascader
                            :show-all-levels="false"
                            :options="catalogOptions"
                             placeholder="选择后台目录"
                             :props="catalogProps"
                            v-model="searchList.catalogIdList"
                            collapse-tags
                            clearable
                          ></el-cascader>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="前台目录">
                          <el-cascader
                            :show-all-levels="false"
                            :options="catagoryOptions"
                             placeholder="选择前台目录"
                             :props="catagoryProps"
                            v-model="searchList.categoryIdList"
                            collapse-tags
                            clearable
                          ></el-cascader>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </el-collapse-transition>
              </el-col>
            </el-row>
            <el-row class="search-row">
              <el-col :span="12" :offset="12" style="text-align: right">
                <el-button
                  @click="closeFilter"
                  :icon="
                    showContent ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
                  "
                  class="white-btn filterClose"
                  >{{ showContent ? '折叠' : '展开' }}</el-button
                >
                <el-button
                  @click="resetForm"
                  icon="el-icon-refresh-left"
                  class="white-btn"
                  >重置</el-button
                >
                <el-button
                  @click="fetchList(true)"
                  icon="el-icon-search"
                  class="dark-btn search-btn"
                  >搜索</el-button
                >
              </el-col>
            </el-row>
          </el-form>
        </div>
      </v-notes>
      <div class="mb-lg">
        <v-table
          :data="tableData"
          ref="table"
          :listLoading="listLoading"
          :loadingText="loadingText"
          :paginationTotal="total"
          v-on:pageSizeChange="pageSizeChange"
          v-on:currentPageChange="currentPageChange"
          v-on:handleSelectionChange="handleSelectionChange"
          border
          pagination
        >
          <div slot="header">
            <el-button
              v-if="$auth('commodityCenter:commodityManagement:add')"
              icon="el-icon-plus"
              class="search-btn"
              @click="addProduct"
            >新增</el-button>
            <el-button
              v-if="$auth('commodityCenter:commodityManagement:shelves')"
              @click="handleCommand('ON')"
              icon="el-icon-sell"
              class="search-btn"
            >上架</el-button>
            <el-button
              v-if="$auth('commodityCenter:commodityManagement:offShelves')"
              @click="handleCommand('OFF')"
              icon="el-icon-sold-out"
              class="search-btn"
            >下架</el-button>
            <el-button
              v-if="$auth('commodityCenter:commodityManagement:export')"
              @click="downloadForm"
              icon="el-icon-download"
              class="search-btn"
            >导出</el-button>
          </div>
          <el-table-column
            type="selection"
            align="center"
            width="45"
          ></el-table-column>
          <el-table-column
            label="商品名称"
            align="center"
            min-width="120"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span
                class="edit-item colorLink"
                @click="getProductDeatil(scope.row.id)"
                >{{ scope.row.productName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="商品图片" align="center">
            <template slot-scope="scope">
              <el-image
                :src="scope.row.defaultImage || ''"
                style="width: 60px; height: 60px; vertical-align: middle"
                fit="fill"
              >
                <div
                  slot="placeholder"
                  class="image-slot"
                  v-loading="true"
                  element-loading-text="加载中"
                ></div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column
            label="SPU编码"
            align="center"
            min-width="150"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.spuCode }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="商品类型"
            align="center"
            min-width="110"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ getDictionaryNameByCode('PRODUCTTYPE', scope.row.productType) }}
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            align="center"
            property="productStatus"
            :formatter="formatPaperType"
            min-width="110"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            label="后台类目"
            prop="catalogName"
            align="center"
            min-width="150"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="前台类目"
            prop="categoryCount"
            align="center"
            min-width="130"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top" v-if="scope.row.categoryNameList" popperClass="table-popper">
                <span v-for="(item,index) in scope.row.categoryNameList" :key="index">
                  {{item}}
                  <span v-if="index!=scope.row.categoryNameList.length-1">/<br></span>
                </span>
                <div slot="reference" class="name-wrapper green">{{scope.row.categoryCount}}</div>
              </el-popover>
              <span v-else>{{ scope.row.categoryCount }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="SKU数量"
            align="center"
            min-width="110"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">{{ scope.row.skuCount }}</template>
          </el-table-column>
          <el-table-column
            label="排序"
            align="center"
            min-width="120"
          >
           <template slot-scope="scope">
             <span v-if="!scope.row.changeSort">{{ scope.row.sort }}</span>
             <div v-else>
              <el-input-number
                v-model="scope.row.sort"
                :controls="false"
                :step-strictly="true"
                :min="0"
                size="mini"
              >
              </el-input-number>
              <i @click="saveSort(scope.row)" class="el-input__icon el-icon-circle-check colorLink"></i>
             </div>
           </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            min-width="140"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">{{
              scope.row.createTime | timestampToChange('time')
            }}</template>
          </el-table-column>
          <el-table-column
            label="更新时间"
            align="center"
            min-width="140"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">{{
              scope.row.updateTime | timestampToChange('time')
            }}</template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            align="center"
            min-width="280"
          >
            <template slot-scope="scope">
              <el-row type="flex" justify="space-around">
                <el-col :span="6">
                  <span
                    class="edit-item colorLink"
                    @click="relatailProduct(scope.row)"
                    ><i class="el-icon-link"></i> 关联商品</span
                  >
                </el-col>
                <el-col :span="6">
                  <span
                    class="edit-item colorLink"
                    @click="editProduct(scope.row)"
                    ><i class="el-icon-edit"></i> 修改</span
                  >
                </el-col>
                <el-col :span="6">
                  <span
                    @click="changeSort(scope.row)"
                    class="edit-item colorLink"
                    >变更排序</span
                  >
                </el-col>
                <el-col :span="6">
                  <span
                    @click="copyProduct(scope.row)"
                    class="edit-item colorLink"
                    >复制商品</span
                  >
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </v-table>
      </div>
    </div>
  </div>
</template>

<script>
import { getLookupItems } from '@/utils/auth'
import { mapGetters } from 'vuex'
import VNotes from '@/components/Notes/index'
import VTable from '@/components/PageTable/index'
import { common } from '@/mixins/common'
import { productList, putOnOff, updateSort, getTree, getCatalogById } from '@/api/product'
// import Ellipsis from '@/components/Ellipsis'
// import { xor } from 'lodash'
export default {
  name: 'productMgmt',
  components: {
    VTable,
    VNotes
  },
  mixins: [common],
  computed: {
    ...mapGetters(['lookupItems'])
  },
  data () {
    return {
      downloadModel: {},
      loadingText: '加载中...',
      loading: false,
      pageLoading: false,
      catalogProps: {
        multiple: true,
        value: 'id',
        label: 'catalogName',
        emitPath: false
      },
      catagoryProps: {
        multiple: true,
        value: 'id',
        label: 'categoryName',
        emitPath: false
      },
      searchList: {
        productName: '',
        spuCode: '',
        spuStatus: '',
        productTypeCode: '',
        catalogIdList: [],
        categoryIdList: []
      },
      tableData: [],
      notFilterData: [],
      catalogOptions: [],
      catagoryOptions: [],
      total: 0,
      pageSize: 10,
      currentPage: 0,
      listLoading: false,
      selection: [],
      showContent: false
    }
  },
  mounted () {
    this.getCatalogSelect()
    this.getCatelogSelect()
    this.fetchList()
  },
  methods: {
    getCatalogSelect () {
      getCatalogById('ALL').then(response => {
        const data = response
        if (Number(data.code) === 1) {
          const obj = data.obj
          obj.forEach(item => {
            if (item.children && item.children.length > 0) {
              item.children.forEach(subItem => {
                if (!(subItem.children && subItem.children.length > 0)) {
                  subItem.disabled = true
                }
              })
            } else {
              item.disabled = true
            }
          })
          this.catagoryOptions = obj
        } else {
          this.$confirm(this.$t(data.code), {
            confirmButtonText: this.$t('confirmOK'),
            showCancelButton: false
          })
        }
      })
        .catch(error => {
          this.$confirm(error, {
            confirmbuttontext: this.$t('confirmOK'),
            showcancelbutton: false
          })
        })
    },
    // 获取catelog列表
    getCatelogSelect () {
      const self = this
      getTree().then(response => {
        const data = response
        if (data) {
          if (Number(data.code) === 1) {
            const obj = data.obj || []
            obj.forEach(item => {
              if (item.children && item.children.length > 0) {
                item.children.forEach(subItem => {
                  if (!(subItem.children && subItem.children.length > 0)) {
                    subItem.disabled = true
                  }
                })
              } else {
                item.disabled = true
              }
            })
            self.catalogOptions = obj
          } else {
            this.$confirm(self.$t(data.code), {
              confirmButtonText: this.$t('confirmOK'),
              showCancelButton: false
            })
          }
        }
      })
    },
    downloadForm () {
      this.listLoading = true
      const self = this
      this.$download('/admin/mdse/product/export', self.downloadModel)
        .then((res) => {
          this.listLoading = false
        })
        .catch((err) => {
          this.$alert(err, 'Download failed')
          this.listLoading = false
        })
    },
    resetForm () {
      this.searchList = {
        productName: '',
        spuCode: '',
        spuStatus: '',
        productTypeCode: '',
        catalogIdList: [],
        categoryIdList: []
      }
      this.catalogIdList = {}
      this.categoryIdList = {}
      this.currentPage = 0
      this.$refs.table.restPage()
      this.fetchList()
    },
    // 格式话表格内容
    formatPaperType: function (row, column, cellValue, index) {
      var paperType = getLookupItems('LookupItemsKey')
      if (paperType) {
        // eslint-disable-next-line no-unused-vars
        for (const key in paperType) {
          const item = paperType[key]
          for (let i = 0; i < item.length; i++) {
            if (item[i].dicCode === cellValue) {
              return item[i].dicName
            }
          }
        }
      }
      return row.paperType
    },
    // 获取列表数据
    fetchList (type) {
      if (!this.$auth('commodityCenter:commodityManagement:list')) {
        // 权限控制
        this.$alert('您没有权限。')
        return false
      }
      if (type) {
        this.$refs.table.restPage()
        this.currentPage = 0
      }
      this.listLoading = true
      const params = {
        ...this.searchList,
        displayLength: this.pageSize,
        displayStart: this.currentPage
      }
      this.downloadModel = JSON.parse(JSON.stringify(params))
      productList(params)
        .then(res => {
          this.listLoading = false
          if (res) {
            if (Number(res.code) === 1) {
              const obj = res.obj
              this.tableData = obj.data || []
              this.notFilterData = obj.data
              this.total = obj.total
            } else {
              this.$confirm(this.$t(res.code), {
                confirmButtonText: '确定',
                showCancelButton: false
              })
            }
          }
        })
    },
    // 每页数据数目改变
    pageSizeChange (size) {
      this.pageSize = size
      this.fetchList()
    },
    // 商品排序
    changeSort (row) {
      if (!this.$auth('commodityCenter:commodityManagement:changeSorting')) {
        // 权限控制
        this.$alert('您没有权限。')
        return false
      }
      this.$set(row, 'changeSort', true)
    },
    saveSort (row) {
      this.listLoading = true
      const datas = {
        id: row.id,
        sort: row.sort
      }
      updateSort(datas).then(res => {
        this.listLoading = false
        if (Number(res.code) === 1) {
          this.$confirm('操作成功', {
            confirmButtonText: '确定',
            showCancelButton: false
          })
          this.fetchList()
        } else {
          this.$confirm(this.$t(res.code), {
            confirmButtonText: '确定',
            showCancelButton: false
          })
        }
      })
    },
    // 当前页改变
    currentPageChange (curPage) {
      this.currentPage = curPage - 1
      this.fetchList()
    },
    // 设置商品上下架操作
    handleCommand (command) {
      const tip =
          command === 'ON'
            ? '是否上架当前所选商品？'
            : '是否下架当前所选商品？'
      if (this.selection.length > 0) {
        const spuIdLists = []
        let flag = false
        this.selection.forEach((item) => {
          spuIdLists.push(item.id)
          if (item.productStatus === 'PRODUCTSTATUS03' && command === 'ON') {
            flag = true
          }
          if (item.productStatus === 'PRODUCTSTATUS04' && command === 'OFF') {
            flag = true
          }
        })
        if (flag) {
          const hasTip =
          command === 'ON'
            ? '当前所选商品中包含已上架商品，请重新选择'
            : '当前所选商品中包含已下架商品，请重新选择'
          this.$alert(hasTip)
          return false
        }
        this.$confirm(tip, {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.listLoading = true
          const params = {
            operationType: command,
            spuIdList: spuIdLists
          }
          putOnOff(params).then(res => {
            if (res) {
              this.listLoading = false
              if (Number(res.code) === 1) {
                this.$confirm('操作成功', {
                  confirmButtonText: '确定',
                  showCancelButton: false
                })
                this.fetchList()
              } else {
                this.$confirm(this.$t(res.code), {
                  confirmButtonText: '确定',
                  showCancelButton: false
                })
              }
            }
          })
        })
      } else {
        this.$alert('请至少选择一项')
        return false
      }
    },
    getProductDeatil (spuId) {
      if (!this.$auth('commodityCenter:commodityManagement:detail')) {
        // 权限控制
        this.$alert('您没有权限。')
        return false
      }
      if (spuId) {
        this.$router.push({
          name: 'productDetail',
          params: { id: spuId, type: 'preview' }
        })
      }
    },
    relatailProduct (spuId) {
      if (!this.$auth('commodityCenter:commodityManagement:associatedGoods')) {
        // 权限控制
        this.$alert('您没有权限。')
        return false
      }
      if (spuId) {
        this.$router.push({
          name: 'productRelation',
          params: { id: spuId, type: 'vehicle' }
        })
      }
    },
    // 点击编辑商品
    editProduct (row) {
      if (!this.$auth('commodityCenter:commodityManagement:modify') || !this.$auth('commodityCenter:commodityManagement:detail')) {
        // 权限控制
        this.$alert('您没有权限。')
        return false
      }
      // 上架的商品无法编辑
      if (row.productStatus === 'PRODUCTSTATUS03' || row.productStatus === 'PRODUCTSTATUS02') {
        this.$alert('已上架/待上架商品无法编辑', {
          confirmButtonText: '确定',
          callback: (action) => {
            return false
          }
        })
        return
      }
      if (row.id) {
        this.$router.push({
          name: 'editProduct',
          params: { id: row.id, type: 'edit' }
        })
      }
    },
    copyProduct (row) {
      if (!this.$auth('commodityCenter:commodityManagement:copy')) {
        // 权限控制
        this.$alert('您没有权限。')
        return false
      }
      if (row.id) {
        this.$router.push({
          name: 'copyProduct',
          params: { id: row.id, type: 'copy' }
        })
      }
    },
    // 表格选择变化事件
    handleSelectionChange (val) {
      this.selection = val
    },
    // 添加商品按钮点击
    addProduct () {
      if (!this.$auth('commodityCenter:commodityManagement:add')) {
        // 权限控制
        this.$alert('您没有权限。')
        return false
      }
      this.$router.push({ name: 'addProduct', params: { id: '' } })
    },
    closeFilter () {
      this.showContent = !this.showContent
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.edit-item {
  cursor: pointer;
}
.producter-center {
  .operate-container {
    display: flex;
    justify-content: space-between;
    justify-items: space-between;
    height: 30px;
    .operate-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      line-height: 30px;
      .el-input {
        margin-bottom: 0;
      }
    }
  }
}
.view-container {
  padding-left: 20px;
  padding-right: 20px;

  .view-container-descrition {
    display: flex;

    .view-container-img {
      width: 270px;
      margin-right: 20px;

      & > .img-item {
        display: flex;
        justify-content: space-between;
        width: 270px;
        margin-top: 10px;
        overflow-x: scroll;
        overflow-y: hidden;
      }
    }
  }
}

.producter-center {
  .stepStyle {
    margin-top: 20px;
    font-size: 16px;
  }

  .inputDiv {
    margin: 0px 0px 15px 0px;
    border: 1px solid #e4e7ed;
    padding: 15px;
    border-radius: 5px;
  }

  .casSty {
    margin-top: 15px;
  }

  .thisStepStyle {
    margin-top: 10px;
    border: 1px solid #e4e7ed;
    border-radius: 5px;
    padding: 15px 15px 0px 15px;
  }

  .spuImage {
    margin-right: 10px;
  }

  .addImageSty {
    float: right;
    font-size: 12px;
    text-align: center;
    margin-bottom: 10px;
  }

  .stepButtonSty {
    margin: auto;
    margin-top: 10px;
  }

  .spuImage {
    width: 200px;
    height: 200px;
  }

  .demo-image {
    clear: both;
  }

  .el-upload-list__item {
    display: inline-block;
    width: 300px;
  }

  .upload-demo {
    margin-top: 10px;
  }

  /deep/ .image-slot {
    height: 60px;
    width: 60px;
    .el-loading-text {
      font-size: 12px;
    }
  }
}

.step3 {
  .el-select {
    width: 100px;
    margin-left: 10px;
  }

  .el-input {
    margin-bottom: 0;
  }

  .step3-operate {
    display: flex;
    justify-content: flex-start;
    line-height: 40px;
    margin-top: 20px;
    margin-bottom: 20px;

    .el-button {
      box-sizing: border-box;
      height: 40px;
    }
  }
}
/deep/ .el-cascader__tags .el-tag {
  max-width: calc(100% - 55px);
}
/deep/ .el-input-number--mini {
  width: calc(100% - 35px);
}
/deep/ .el-cascader{
  width: 100%;
}
</style>
